/**
 * Created with IntelliJ IDEA.
 * User: jiaou
 * Date: 15-5-27
 * Time: 下午6:07
 * To change this template use File | Settings | File Templates.
 */

var JSONFormat = (function () {
    var _toString = Object.prototype.toString;

    function format(object, indent_count) {
        var html_fragment = '';
        switch (_typeof(object)) {
            case 'Null' :
                0
                html_fragment = _format_null(object);
                break;
            case 'Boolean' :
                html_fragment = _format_boolean(object);
                break;
            case 'Number' :
                html_fragment = _format_number(object);
                break;
            case 'String' :
                html_fragment = _format_string(object);
                break;
            case 'Array' :
                html_fragment = _format_array(object, indent_count);
                break;
            case 'Object' :
                html_fragment = _format_object(object, indent_count);
                break;
        }
        return html_fragment;
    };
    function _format_null(object) {
        return '<span class="json_null">null</span>';
    }

    function _format_boolean(object) {
        return '<span class="json_boolean">' + object + '</span>';
    }

    function _format_number(object) {
        return '<span class="json_number">' + object + '</span>';
    }

    function _format_string(object) {
        if (0 <= object.search(/^http/)) {
            object = '<a href="' + object + '" target="_blank" class="json_link">' + object + '</a>'
        }
        return '<span class="json_string">"' + object + '"</span>';
    }

    function _format_array(object, indent_count) {
        var tmp_array = [];
        for (var i = 0, size = object.length; i < size; ++i) {
            tmp_array.push(indent_tab(indent_count) + format(object[i], indent_count + 1));
        }
        return '[\n'
            + tmp_array.join(',\n')
            + '\n' + indent_tab(indent_count - 1) + ']';
    }

    function _format_object(object, indent_count) {
        var tmp_array = [];
        for (var key in object) {
            tmp_array.push(indent_tab(indent_count) + '<span class="json_key">"' + key + '"</span>:' + format(object[key], indent_count + 1));
        }
        return '{\n'
            + tmp_array.join(',\n')
            + '\n' + indent_tab(indent_count - 1) + '}';
    }

    function indent_tab(indent_count) {
        return (new Array(indent_count + 1)).join(' ');
    }

    function _typeof(object) {
        var tf = typeof object,
            ts = _toString.call(object);
        return null === object ? 'Null' :
            'undefined' == tf ? 'Undefined' :
                'boolean' == tf ? 'Boolean' :
                    'number' == tf ? 'Number' :
                        'string' == tf ? 'String' :
                            '[object Function]' == ts ? 'Function' :
                                '[object Array]' == ts ? 'Array' :
                                    '[object Date]' == ts ? 'Date' : 'Object';
    };
    function loadCssString() {
        var style = document.createElement('style');
        style.type = 'text/css';
        var code = Array.prototype.slice.apply(arguments).join('');
        try {
            style.appendChild(document.createTextNode(code));
        } catch (ex) {
            style.styleSheet.cssText = code;
        }
        document.getElementsByTagName('head')[0].appendChild(style);
    }

    loadCssString(
        '.json_key{ color: purple;}',
        '.json_null{color: red;}',
        '.json_string{ color: #077;}',
        '.json_link{ color: #717171;}',
        '.json_array_brackets{}');
    var _JSONFormat = function (origin_data) {
        this.data = 'string' != typeof origin_data ? origin_data :
            JSON && JSON.parse ? JSON.parse(origin_data) : eval('(' + origin_data + ')');
    };
    _JSONFormat.prototype = {
        constructor: JSONFormat,
        toString: function () {
            return format(this.data, 1);
        }
    }
    return _JSONFormat;
})();
function create_result_contatiner() {
    var $result = $('<pre id="result" style=" width: 100%; height: 100%; overflow: scroll; overflow-x: scroll; overflow-y:scroll"></pre>')
    var $result_container = $('<div id="result_container" style="position: fixed; top: 1%; right: 8px; width: 5%; height: 97%; margin: 0; padding: 0; border:1px solid skyblue; background: #f8f8f8; line-height: 1.2em; font-size: 14px; cursor: pointer;"></div>');
    $result_container.append($result);
    $result_container.hover(function () {
        $(this).stop(true).animate({width: '50%'}, 'slow');
    }, function () {
        $(this).stop(true).animate({width: '5%'}, 'slow');
    });
    $('body').append($result_container);
    return [$result_container, $result];
}
(function request_intercept(args) {
    var $result_container = args[0],
        $result = args[1];
    $('form *[type="submit"]').bind('click', function () {
        var _form = $(this).parents('form'),
            _action = (_form.attr('action') || './'),
            _method = (_form.attr('method') || 'get').toLowerCase(),
            _params = {};
        _form.find('input[type="text"]').each(function () {
            var item = $(this);
            _params[item.attr('name')] = item.val();
        });
        $['get' == _method ? 'get' : 'post'](_action, _params, function (response) {
            try {
                var j = new JSONFormat(JSON && JSON.parse ? JSON.parse(response) : eval('(' + response + ')'));
                $result.html(j.toString());
            } catch (e) {
                $result.html($result.text(response).html());
            }
            $result_container.stop(true).animate({width: '50%'}, 'slow');
        });
        return false;
    });
})(
        create_result_contatiner()
    );

function myFormatJson(txt,compress/*是否为压缩模式*/){/* 格式化JSON源码(对象转换为JSON文本) */
    var indentChar = '    ';
    if(/^\s*$/.test(txt)){
        alert('数据为空,无法格式化! ');
        return;
    }
    try{var data=eval('('+txt+')');}
    catch(e){
        alert('数据源语法错误,格式化失败! 错误信息: '+e.description,'err');
        return;
    };
    var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0;

    var notify=function(name,value,isLast,indent/*缩进*/,formObj){
        nodeCount++;/*节点计数*/
        for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 缩进HTML */
        tab=compress?'':tab;/*压缩模式忽略缩进*/
        maxDepth=++indent;/*缩进递增并记录*/
        if(value&&value.constructor==Array){/*处理数组*/
            draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*缩进'[' 然后换行*/
            for (var i=0;i<value.length;i++)
                notify(i,value[i],i==value.length-1,indent,false);
            draw.push(tab+']'+(isLast?line:(','+line)));/*缩进']'换行,若非尾元素则添加逗号*/
        }else   if(value&&typeof value=='object'){/*处理对象*/
            draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*缩进'{' 然后换行*/
            var len=0,i=0;
            for(var key in value)len++;
            for(var key in value)notify(key,value[key],++i==len,indent,true);
            draw.push(tab+'}'+(isLast?line:(','+line)));/*缩进'}'换行,若非尾元素则添加逗号*/
        }else{
            if(typeof value=='string')value='"'+value+'"';
            draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line);
        };
    };
    var isLast=true,indent=0;
    notify('',data,isLast,indent,false);
    return draw.join('');
}


